<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<uni-icons type="arrowleft" size="24" @click="goBack"></uni-icons>
			<text class="title">添加零食</text>
			<view style="width: 24px;"></view>
		</view>

		<!-- 表单内容 -->
		<scroll-view class="form-container" scroll-y>
			<view class="form-content">
				<view class="form-card" v-if="!submitSuccess">
					<!-- 图片上传 -->
					<view class="upload-section">
						<text class="section-title">零食图片</text>
						<view class="upload-box" @click="chooseImage">
							<image v-if="localImagePath" :src="localImagePath" class="preview-image" mode="aspectFill">
							</image>
							<view v-else class="upload-placeholder">
								<uni-icons type="camera" size="36" color="#999"></uni-icons>
								<text class="upload-text">点击上传图片</text>
							</view>
						</view>
						<progress v-if="uploadProgress > 0 && uploadProgress < 100" :percent="uploadProgress"
							stroke-width="3" activeColor="#4a8fe7" class="upload-progress" />
						<text class="upload-tip" v-if="isUploading">
							上传中...{{ uploadProgress }}%
						</text>
					</view>

					<!-- 基本信息 -->
					<view class="form-section">
						<text class="section-title">基本信息</text>
						<uni-forms ref="form" :model="formData" :rules="rules">
							<uni-forms-item label="零食名称" name="name" required>
								<uni-easyinput v-model="formData.name" placeholder="请输入零食名称" />
							</uni-forms-item>

							<uni-forms-item label="分类" name="category_id" required>
								<uni-data-select v-model="formData.category_id" :localdata="categories" :clear="false"
									placeholder="请选择分类"></uni-data-select>
							</uni-forms-item>

							<view class="price-row">
								<uni-forms-item label="售价" name="price" required class="price-item">
									<uni-easyinput v-model="formData.price" placeholder="0.00" type="digit">
										<template v-slot:right>
											<text class="input-suffix">元</text>
										</template>
									</uni-easyinput>
								</uni-forms-item>

								<uni-forms-item label="成本价" name="cost_price" class="price-item">
									<uni-easyinput v-model="formData.cost_price" placeholder="0.00" type="digit">
										<template v-slot:right>
											<text class="input-suffix">元</text>
										</template>
									</uni-easyinput>
								</uni-forms-item>
							</view>

							<!-- 新增数量字段 -->
							<uni-forms-item label="库存数量" name="quantity" required>
								<uni-easyinput v-model="formData.quantity" placeholder="请输入库存数量" type="number">
									<template v-slot:right>
										<text class="input-suffix">件</text>
									</template>
								</uni-easyinput>
							</uni-forms-item>

							<uni-forms-item label="状态" name="status">
								<uni-data-checkbox v-model="formData.status" :localdata="statusOptions" />
							</uni-forms-item>
						</uni-forms>
					</view>

					<!-- 描述信息 -->
					<view class="form-section">
						<text class="section-title">详细描述</text>
						<uni-forms-item name="description">
							<uni-easyinput v-model="formData.description" placeholder="请输入零食的详细描述信息..." type="textarea"
								autoHeight />
						</uni-forms-item>
					</view>
				</view>

				<!-- 成功提示 -->
				<view class="success-card" v-if="submitSuccess">
					<view class="success-icon">
						<uni-icons type="checkmarkempty" size="48" color="#4a8fe7"></uni-icons>
					</view>
					<text class="success-title">添加成功！</text>
					<text class="success-message">{{ successMessage }}</text>

					<image v-if="localImagePath" :src="localImagePath" class="success-preview" mode="aspectFill"></image>

					<view class="success-info">
						<view class="info-item">
							<text class="info-label">零食名称：</text>
							<text class="info-value">{{ formData.name }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">分类：</text>
							<text class="info-value">{{ formData.category_name }}</text>
						</view>
						<view class="info-item">
							<text class="info-label">售价：</text>
							<text class="info-value">{{ formData.price }}元</text>
						</view>
						<view class="info-item">
							<text class="info-label">库存数量：</text>
							<text class="info-value">{{ formData.quantity }}件</text>
						</view>
						<view class="info-item">
							<text class="info-label">状态：</text>
							<text class="info-value">{{ formData.status ? '在售' : '下架' }}</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 提交按钮 -->
		<view class="submit-btn-container">
			<template v-if="!submitSuccess">
				<button class="submit-btn" @click="submitForm" :disabled="isSubmitting">
					<text v-if="!isSubmitting">保存零食</text>
					<view v-else class="loading-content">
						<uni-load-more status="loading" color="#fff" :icon-size="16"></uni-load-more>
						<text>提交中...{{ uploadProgress }}%</text>
					</view>
				</button>
			</template>
			<template v-else>
				<button class="continue-btn" @click="resetForm">
					<text>继续添加</text>
				</button>
				<button class="back-btn" @click="goBack">
					<text>返回列表</text>
				</button>
			</template>
		</view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				isSubmitting: false,
				isUploading: false,
				uploadProgress: 0,
				localImageFile: null,
				localImagePath: '',
				submitSuccess: false,
				successMessage: '',
				formData: {
					name: '',
					category_id: '',
					category_name: '',
					price: '',
					cost_price: '',
					quantity: '', // 新增数量字段
					description: '',
					status: 1
				},
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '请输入零食名称'
						}, {
							minLength: 2,
							maxLength: 100,
							errorMessage: '名称长度在2-100个字符之间'
						}]
					},
					category_id: {
						rules: [{
							required: true,
							errorMessage: '请选择分类'
						}]
					},
					price: {
						rules: [{
							required: true,
							errorMessage: '请输入售价'
						}, {
							format: 'number',
							errorMessage: '请输入有效的价格'
						}, {
							minimum: 0.01,
							errorMessage: '售价必须大于0'
						}]
					},
					cost_price: {
						rules: [{
							format: 'number',
							errorMessage: '请输入有效的价格'
						}, {
							minimum: 0,
							errorMessage: '成本价不能为负数'
						}]
					},
					quantity: {
						rules: [{
							required: true,
							errorMessage: '请输入库存数量'
						}, {
							format: 'number',
							errorMessage: '请输入有效的数字'
						}, {
							minimum: 0,
							errorMessage: '数量不能为负数'
						}, {
							maximum: 99999,
							errorMessage: '数量不能超过99999'
						}]
					}
				},
				categories: [{
						value: 1,
						text: "膨化食品"
					},
					{
						value: 2,
						text: "糖果巧克力"
					},
					{
						value: 3,
						text: "饮料"
					},
					{
						value: 4,
						text: "饼干糕点"
					}
				],
				statusOptions: [{
						value: 1,
						text: "在售"
					},
					{
						value: 0,
						text: "下架"
					}
				]
			}
		},
		computed: {
			baseApiUrl() {
				return globalVariable;
			}
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},

			async chooseImage() {
				try {
					const fileInput = document.createElement('input');
					fileInput.type = 'file';
					fileInput.accept = 'image/*';
					fileInput.style.display = 'none';

					const file = await new Promise((resolve, reject) => {
						fileInput.addEventListener('change', (e) => {
							if (e.target.files && e.target.files.length > 0) {
								resolve(e.target.files[0]);
							} else {
								reject(new Error('未选择图片'));
							}
						});
						fileInput.click();
					});

					if (!file.type.startsWith('image/')) {
						throw new Error('请选择图片文件');
					}

					const maxSize = 10 * 1024 * 1024;
					if (file.size > maxSize) {
						throw new Error(`图片大小不能超过${maxSize/1024/1024}MB`);
					}

					this.isUploading = true;
					uni.showLoading({
						title: '处理图片中...',
						mask: true
					});

					const compressedFile = await this.compressImage(file);
					this.localImageFile = compressedFile;
					this.localImagePath = URL.createObjectURL(compressedFile);

					uni.showToast({
						title: '图片已选择',
						icon: 'success'
					});
				} catch (error) {
					console.error('图片处理失败:', error);
					uni.showToast({
						title: error.message || '图片处理失败',
						icon: 'none'
					});
				} finally {
					this.isUploading = false;
					uni.hideLoading();
				}
			},

			compressImage(file) {
				return new Promise((resolve, reject) => {
					const img = new Image();
					const reader = new FileReader();

					reader.onload = (e) => {
						img.src = e.target.result;
					};

					img.onload = () => {
						try {
							const maxSize = globalVariable.imageSettings?.maxSize || 800;
							let width = img.width;
							let height = img.height;

							if (width > height) {
								if (width > maxSize) {
									height *= maxSize / width;
									width = maxSize;
								}
							} else {
								if (height > maxSize) {
									width *= maxSize / height;
									height = maxSize;
								}
							}

							const canvas = document.createElement('canvas');
							canvas.width = width;
							canvas.height = height;
							const ctx = canvas.getContext('2d');

							ctx.fillStyle = '#ffffff';
							ctx.fillRect(0, 0, width, height);
							ctx.drawImage(img, 0, 0, width, height);

							const compressQuality = globalVariable.imageSettings?.compressQuality || 0.7;
							canvas.toBlob(
								(blob) => {
									if (!blob) {
										reject(new Error('图片压缩失败'));
										return;
									}

									const compressedFile = new File(
										[blob],
										file.name,
										{
											type: file.type,
											lastModified: Date.now()
										}
									);

									resolve(compressedFile);
								},
								file.type,
								compressQuality
							);
						} catch (error) {
							reject(new Error('图片处理失败: ' + error.message));
						}
					};

					img.onerror = () => {
						reject(new Error('图片加载失败'));
					};

					reader.onerror = () => {
						reject(new Error('文件读取失败'));
					};

					reader.readAsDataURL(file);
				});
			},

			async submitForm() {
				try {
					await this.$refs.form.validate();
					this.isSubmitting = true;
					uni.showLoading({
						title: '提交中...',
						mask: true
					});

					const selectedCategory = this.categories.find(
						item => item.value === this.formData.category_id
					);
					this.formData.category_name = selectedCategory ? selectedCategory.text : '';

					const formData = new FormData();

					if (this.localImageFile) {
						formData.append('file', this.localImageFile);
					}

					// 添加所有表单数据，包括新增的quantity字段
					for (const key in this.formData) {
						if (key !== 'image_url') {
							formData.append(key, this.formData[key]);
						}
					}

					const response = await new Promise((resolve, reject) => {
						const xhr = new XMLHttpRequest();
						xhr.open('POST', `${this.baseApiUrl}/addSnack`, true);

						xhr.upload.onprogress = (e) => {
							if (e.lengthComputable) {
								this.uploadProgress = Math.round((e.loaded / e.total) * 100);
								uni.showLoading({
									title: `上传中 ${this.uploadProgress}%`,
									mask: true
								});
							}
						};

						xhr.onload = () => {
							if (xhr.status >= 200 && xhr.status < 300) {
								try {
									resolve({
										statusCode: xhr.status,
										data: JSON.parse(xhr.responseText)
									});
								} catch (e) {
									reject(new Error('响应解析失败'));
								}
							} else {
								reject(new Error(`请求失败，状态码: ${xhr.status}`));
							}
						};

						xhr.onerror = () => {
							reject(new Error('网络请求失败'));
						};

						xhr.send(formData);
					});

					const {
						statusCode,
						data
					} = response;
					if (statusCode === 200) {
						if (data.status === 1) {
							this.successMessage = data.data.message || '零食已成功添加';
							this.submitSuccess = true;

							uni.showToast({
								title: '添加成功',
								icon: 'success',
								duration: 2000
							});
						} else {
							throw new Error(data.message || '添加失败');
						}
					} else {
						throw new Error(`请求失败，状态码: ${statusCode}`);
					}
				} catch (error) {
					console.error('提交失败:', error);
					uni.showToast({
						title: error.message || '提交失败',
						icon: 'none',
						duration: 3000
					});
				} finally {
					this.isSubmitting = false;
					this.uploadProgress = 0;
					uni.hideLoading();
				}
			},

			resetForm() {
				this.submitSuccess = false;

				if (this.$refs.form && this.$refs.form.resetFields) {
					this.$refs.form.resetFields();
				}

				this.localImageFile = null;
				this.localImagePath = '';
				this.formData = {
					name: '',
					category_id: '',
					category_name: '',
					price: '',
					cost_price: '',
					quantity: '', // 重置数量字段
					description: '',
					status: 1
				};

				if (this.$refs.form) {
					this.$refs.form.clearValidate();
				}
			}
		},

		beforeDestroy() {
			if (this.localImagePath) {
				URL.revokeObjectURL(this.localImagePath);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f7fa;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 12px 15px;
		background-color: #fff;
		box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
		position: sticky;
		top: 0;
		z-index: 10;
		flex-shrink: 0;

		.title {
			font-size: 18px;
			font-weight: bold;
			color: #333;
		}
	}

	.form-container {
		flex: 1;
		overflow: auto;
		-webkit-overflow-scrolling: touch;
		padding-bottom: 80px;
	}

	.form-content {
		padding: 15px;
	}

	.form-card {
		background-color: #fff;
		border-radius: 12px;
		padding: 16px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		margin-bottom: 15px;
	}

	.form-section {
		margin-bottom: 20px;

		.section-title {
			display: block;
			font-size: 16px;
			font-weight: bold;
			color: #333;
			margin-bottom: 12px;
			padding-left: 8px;
			border-left: 4px solid #4a8fe7;
		}
	}

	.upload-section {
		margin-bottom: 20px;

		.section-title {
			display: block;
			font-size: 16px;
			font-weight: bold;
			color: #333;
			margin-bottom: 12px;
			padding-left: 8px;
			border-left: 4px solid #4a8fe7;
		}

		.upload-box {
			width: 100%;
			height: 180px;
			border: 2px dashed #e0e0e0;
			border-radius: 8px;
			display: flex;
			align-items: center;
			justify-content: center;
			overflow: hidden;
			background-color: #fafafa;
			transition: all 0.3s;

			&:active {
				background-color: #f0f0f0;
			}

			.preview-image {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}

			.upload-placeholder {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.upload-text {
					font-size: 14px;
					color: #999;
					margin-top: 8px;
				}
			}
		}

		.upload-progress {
			margin-top: 8px;
		}

		.upload-tip {
			display: block;
			font-size: 12px;
			color: #666;
			text-align: center;
			margin-top: 8px;
		}
	}

	.price-row {
		display: flex;
		gap: 12px;
		margin-bottom: -10px;

		.price-item {
			flex: 1;
		}
	}

	.input-suffix {
		color: #999;
		padding: 0 8px;
		font-size: 14px;
	}

	.submit-btn-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 12px 15px;
		background-color: #fff;
		border-top: 1px solid #eee;
		display: flex;
		flex-direction: column;
		gap: 10px;
		box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
	}

	.submit-btn {
		width: 100%;
		background: linear-gradient(135deg, #4a8fe7, #6a5acd);
		color: white;
		border: none;
		border-radius: 25px;
		height: 48px;
		line-height: 48px;
		font-size: 16px;
		font-weight: 500;
		box-shadow: 0 4px 12px rgba(74, 143, 231, 0.3);
		transition: all 0.3s;

		&[disabled] {
			opacity: 0.7;
		}

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2px 8px rgba(74, 143, 231, 0.4);
		}
	}

	.continue-btn {
		background: linear-gradient(135deg, #4a8fe7, #6a5acd);
		color: white;
		border: none;
		border-radius: 25px;
		height: 48px;
		line-height: 48px;
		font-size: 16px;
		font-weight: 500;
		box-shadow: 0 4px 12px rgba(74, 143, 231, 0.3);
		transition: all 0.3s;

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2px 8px rgba(74, 143, 231, 0.4);
		}
	}

	.back-btn {
		background: #fff;
		color: #4a8fe7;
		border: 1px solid #4a8fe7;
		border-radius: 25px;
		height: 48px;
		line-height: 48px;
		font-size: 16px;
		font-weight: 500;
		transition: all 0.3s;

		&:active {
			transform: scale(0.98);
			background: #f5f9ff;
		}
	}

	.success-card {
		background-color: #fff;
		border-radius: 12px;
		padding: 20px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
		text-align: center;
	}

	.success-icon {
		width: 72px;
		height: 72px;
		border-radius: 50%;
		background-color: #f0f7ff;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 12px;
	}

	.success-title {
		font-size: 18px;
		font-weight: bold;
		color: #333;
		margin-bottom: 6px;
		display: block;
	}

	.success-message {
		font-size: 14px;
		color: #666;
		margin-bottom: 16px;
		display: block;
	}

	.success-preview {
		width: 100%;
		height: 160px;
		border-radius: 8px;
		margin-bottom: 16px;
		object-fit: cover;
		border: 1px solid #eee;
	}

	.success-info {
		text-align: left;
		background-color: #f9f9f9;
		border-radius: 8px;
		padding: 12px;
	}

	.info-item {
		display: flex;
		margin-bottom: 8px;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.info-label {
		font-size: 13px;
		color: #666;
		width: 70px;
	}

	.info-value {
		font-size: 13px;
		color: #333;
		font-weight: 500;
		flex: 1;
	}

	.loading-content {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 6px;
		font-size: 14px;
	}

	/* 针对不同屏幕尺寸的适配 */
	@media (max-height: 600px) {
		.upload-box {
			height: 150px !important;
		}
		
		.success-preview {
			height: 120px !important;
		}
	}

	@media (min-width: 768px) {
		.form-content {
			max-width: 600px;
			margin: 0 auto;
		}
	}
</style>